from chat_bot.models.intent_fasttext.predict import FastTextModel
from chat_bot.models.NER.predict import NERPredictor
from chat_bot.answer_search.answer_searcher import AnswerSearcher


def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]

    return inner


@singleton
class ChatBot(object):
    def __init__(self):
        self.NER_predictor = NERPredictor()
        print('实体识别模型加载完成')
        # self.intentModel = IntentModel()
        self.intentModel = FastTextModel()
        print('意图识别模型加载完成')
        self.answer_searcher = AnswerSearcher()
        print('答案搜索器加载完成')

    def __call__(self, text, *args, **kwargs):
        query = self.parser(text)
        return self.answer_searcher.get_answer(query)

    def get_intent(self, text):
        return self.intentModel.predict(text)
        # return self.FastTextModel.predict(text)

    def get_entities(self, text):
        return self.NER_predictor.predict(text)

    def parser(self, text):
        msg = {
            'text': text,
            'intent': self.get_intent(text),
            'entities': self.get_entities(text)
        }

        if '小番茄' in text:
            msg['entities']["Crop"] = ['小番茄']
        return msg


if __name__ == '__main__':
    while True:
        c = ChatBot()
        t = input(':')
        print(c(t))
